package com.kin207.netty.listener.server.handle;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.collections.iterators.EntrySetMapIterator;

import com.kin207.netty.context.RequestContext;
import com.kin207.netty.handle.IMessageHandle;
import com.kin207.netty.listener.server.handle.vo.SessionListReqVo;
import com.kin207.netty.server.IServer;
import com.kin207.netty.session.Session;
import com.kin207.netty.util.StringParseUtils;

public class SessionListMessageHandle implements IMessageHandle<SessionListReqVo> {

	public String name() {
		return "/session/list";
	}

	public Class paramClass() {
		return SessionListReqVo.class;
	}

	public void handle(SessionListReqVo param) {
		RequestContext req = RequestContext.curr.get();
		StringParseUtils spu = new StringParseUtils();
		int pageSize = spu.set(param.getPageSize()).isEmpty()?20:spu.getInt();
		int pageIndex = spu.set(param.getPageIndex()).isEmpty()?1:spu.getInt();
		int end = pageIndex*pageSize;
		int begin = end-pageSize;
		
		
		int i = 0;
		StringBuffer msg = new StringBuffer();
		Map<String,Session> sessions = req.getServer().getSessionManager().getSessions();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(Entry<String, Session> item : sessions.entrySet()){
			if(i>=begin && i<end){
				Session s = item.getValue();
				msg.append("id=").append(s.getId()).append("\t")
				.append("name=").append(s.getName()).append("\t")
				.append("lastActive=").append(sdf.format(s.getLastActive())).append("\t")
				.append("groups=").append(s.getGroups()).append("\n");
			}
			i++;
			if(i>=end){
				break;
			}
		}
		msg.append("pageIndex=").append(pageIndex).append("\t");
		msg.append("pageSize=").append(pageSize).append("\t");
		msg.append("total=").append(sessions.size()).append("\n");
		req.wirte(msg.toString());
		
	}

}
